using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Windows.Forms;

namespace IPAMS.Views
{
    /// <summary>
    /// This is an editor for the Quotes table. It enables loading from a file,
    ///saving to a file and more
    /// </summary>
    public partial class QuotesEditor : UserControl
    {
        public DSIPAMS.DTQuotesDataTable quotes;
        string[] quotesHeaders;

        private const string SHOW_ALL = "Show All";
        /// <summary>
        /// Initializes a new instance of the <see cref="QuotesEditor"/> class.
        /// </summary>
        public QuotesEditor()
        {
            InitializeComponent();
            InitializeComponentExtended();
        }

        /// <summary>
        /// Initializes the component extended.
        /// </summary>
        private void InitializeComponentExtended()
        {
            quotes = new DSIPAMS.DTQuotesDataTable();
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the comboBoxSelectStock control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void comboBoxSelectStock_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxSelectStock.Text == SHOW_ALL)
            {
                dgvQuote.DataSource = quotes;
                return;
            }


            else if (comboBoxSelectStock.Text != null && comboBoxSelectStock.Text != string.Empty)
            {
                string expression =
               string.Format("QUOTE_STOCK_SYMBOL = '{0}'", comboBoxSelectStock.SelectedItem);
                string sorting = "QUOTE_DATE ASC";
                dgvQuote.DataSource = quotes.Select(expression, sorting);

            }
        }

        /// <summary>
        /// Handles the DataSourceChanged event of the dgvQuote control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void dgvQuote_DataSourceChanged(object sender, EventArgs e)
        {
            dgvQuote.Refresh();
        }

        /// <summary>
        /// Loads the data from a file.
        /// </summary>
        /// <param name="dataFilePath">The data file path.</param>
        /// <returns>a DataTable with the file data</returns>
        public DataTable LoadData(string dataFilePath)
        {

            if (File.Exists(dataFilePath))
            {
                StreamReader sr = new StreamReader(dataFilePath);
                quotesHeaders = sr.ReadLine().Split(',');

                while (true)
                {
                    string quote = sr.ReadLine();
                    if (quote == string.Empty || quote == null || quote == @",,,") break;
                    string[] quoteInfo = quote.Split(',');
                    if (quoteInfo.Length != 4) continue;
                    CultureInfo ci = new CultureInfo("he-IL");
                    quotes.AddDTQuotesRow(DateTime.Parse(quoteInfo[0], ci.DateTimeFormat), quoteInfo[1], Convert.ToDouble(quoteInfo[2]), quoteInfo[3]);
                }
                sr.Close();
                
                Text = dataFilePath;
            
                dgvQuote.DataSource = quotes;
                for (int index = 0; index < quotesHeaders.Length; index++)
                {
                    dgvQuote.Columns[index].HeaderText = quotesHeaders[index];
                }



                foreach (DataGridViewColumn column in dgvQuote.Columns)
                {
                    column.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
                }
            }
         
       
            return quotes;
        }

        /// <summary>
        /// Sets the stocks list in the comboBoxSelectStock selection.
        /// </summary>
        /// <param name="stocks">The list of stocks names.</param>
        public void SetStocksFilterSelection( List<string>  stocks)
        {
            stocks.Add(SHOW_ALL);
            if (stocks.Count == 0) return;
            else 
                foreach(string stock in stocks)
                {
                    comboBoxSelectStock.Items.Add(stock);
                }

         }

         /// <summary>
         /// Saves the data to a file.
         /// </summary>
         /// <param name="dataFilePath">The data file path.</param>
        public void SaveData(string dataFilePath)
        {
            StreamWriter sw = new StreamWriter(dataFilePath);
            string fileContent = quotesHeaders + Environment.NewLine;
            foreach(DSIPAMS.DTQuotesRow quote in quotes)
            {
                fileContent += string.Format("{0},{1},{2},{3}" + Environment.NewLine, quote[0], quote[1], quote[2], quote[3]);
            }
            sw.Write(fileContent);
           
            sw.Close();
        }

    }
}
